package com.starbaba.system.userauthority.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.base.common.util.AESUtils;
import com.opensymphony.xwork2.Action;
import com.starbaba.core.exception.TaskException;
import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.service.CommonService;
import com.starbaba.core.utils.IPUtil;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.constant.Constants;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.sequence.Sequence;
import com.starbaba.system.attach.model.AttachVO;
import com.starbaba.system.common.AsynchronousTaskFactory;
import com.starbaba.system.index.dao.QueryUserGroupComidStrategy;
import com.starbaba.system.index.dao.QueryUserOfGroupStrategy;
import com.starbaba.system.index.dao.QueryUserOfRoleStrategy;
import com.starbaba.system.loginlog.model.LoginLogVO;
import com.starbaba.system.menu.model.MenuVO;
import com.starbaba.system.user.model.UserVO;
import com.starbaba.system.usergroupcontrol.model.UsergroupControlVO;

/**
 * 系统认证功能页面
 *
 * @Copyright: Copyright (c) 2006
 * @Company: Revenco Tech Ltd.
 * @anthor chenminhui<chenminhui@revenco.com>
 * @since 2014-9-12 下午03:32:17
 * @version V1.0
 */
@Component
@SuppressWarnings({"rawtypes","unchecked"})
public class AuthServiceImpl implements AuthService {

	private Log log = LogFactory.getLog(getClass());

	private CommonService service;
	protected Class<?> voClass;

	private static final String COOKIE_NAME = "AUTOBG";

	private static final String AESKEY = "EDA0D779538282911BBC61651A186621";

	private static final String COOKIE_SEPARATOR = "_";

	// 有效期15天
	private static final long EFFERT_LAST = 1000 * 60 * 60 * 24 * 15;

	@Override
	public UserVO getOperator() {
		// return (UserVO)
		// Struts2Utils.getSession().getAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
		return (UserVO) Struts2Utils.getSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
	}

	public static void main(String[] args) {
		// huhaotian
		String key = AESUtils.encrypt("haotianhu0730", AESKEY);
		System.out.println(key);
	}

	@Override
	public String login(String opercode, String password, String vcode, String autologin) throws Exception {
		/* 验证码判断功能 */
		String svcode = (String) Struts2Utils.getSessionAttribute("vacode");
		String autoValue = null;
		if (StringUtils.isEmpty(opercode) && StringUtils.isEmpty(password)) {
			Cookie[] cookies = Struts2Utils.getRequest().getCookies();
			for (Cookie c : cookies) {
				if (COOKIE_NAME.equals(c.getName())) {
					autoValue = c.getValue();
					break;
				}
			}

			if (autoValue != null) {
				String cookieValue = AESUtils.decrypt(autoValue, AESKEY);
				String[] temps = cookieValue.split(COOKIE_SEPARATOR);
				if (temps.length > 2) {
					Long time = Long.valueOf(temps[2]);
					if (time > System.currentTimeMillis()) {
						opercode = temps[0];
						password = temps[1];
						autologin = null;
					}
				}
			} else {
				return Action.ERROR;
			}
		} else {
		    // 比较验证码
			// TODO 测试先放开验证码的验证
			if (!StringUtils.equalsIgnoreCase(vcode, svcode)) {
				this.addErrorMessage(Constants.ERRORMESSAGE_1);
				Struts2Utils.getRequest().setAttribute("vacode_error", "验证码不正确");
				return Action.ERROR;
			}

		}

		/**
		 * 查询本地数据库用户信息,确认用户loginId
		 */
		Date currenttime = new Date();
		String hql = "from UserVO u where u.userid = ? and u.status = ? and u.stopdate >= ? and u.startdate <= ?";
		List<UserVO> userList = (List<UserVO>) this.getService().doFindByHQL(hql,
				new Object[] { opercode, WebConstants.STATUS_VALID, currenttime, currenttime });

		UserVO userVO = null;
		if (null != userList && userList.size() > 0) {
			userVO = userList.get(0);
		}

		if (null == userVO) {// 本地和远程都无该用户信息,用户不合法
			this.addErrorMessage(Constants.ERRORMESSAGE_2);
			return Action.ERROR;
		}

		/**
		 * 检查用户密码
		 */
		// String pwdMd5 = MD5Encrypt.getMD5Password(password);
		if (!StringUtils.equalsIgnoreCase(password, userVO.getPasswd())) {
			this.addErrorMessage(Constants.ERRORMESSAGE_3);
			return Action.ERROR;
		}

		/**
		 * 查询用户角色
		 */
		QueryUserOfRoleStrategy strategy = new QueryUserOfRoleStrategy(userVO);
		List<Long> roleIdList = (List<Long>) this.getService().doProcess(strategy);
		userVO.setRoleIdList(roleIdList);

		/**
		 * 查询用户组
		 */
		QueryUserOfGroupStrategy userGroupStrategy = new QueryUserOfGroupStrategy(userVO);
		List<Long> userGrouplist = (List<Long>) this.getService().doProcess(userGroupStrategy);
		userVO.setGourpIdList(userGrouplist);

		/**
		 * 查询是否管理员
		 */
		QueryUserGroupComidStrategy userGroupComidStrategy = new QueryUserGroupComidStrategy(userVO);
		List<Long> userGroupComidlist = (List<Long>) this.getService().doProcess(userGroupComidStrategy);
		if (userGroupComidlist.size() > 0) {
			userVO.setIsManager(true);
		} else {
			userVO.setIsManager(false);
		}

		// 写入用户session
		// Struts2Utils.getSession().setAttribute(WebConstants.SESSION_ATTRIBUTE_USER,
		// userVO);

		Struts2Utils.setSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER, userVO);

		if (autologin != null) {
			long exir = System.currentTimeMillis() + EFFERT_LAST;
			autoValue = opercode + COOKIE_SEPARATOR + password + COOKIE_SEPARATOR + exir;
			String cookieValue = AESUtils.encrypt(autoValue, AESKEY);
			Cookie autoLoginCookie = new Cookie(COOKIE_NAME, cookieValue);
			autoLoginCookie.setMaxAge((int) EFFERT_LAST);
			Struts2Utils.getResponse().addCookie(autoLoginCookie);

		}

		createLoginLog(userVO.getUserid());

		return Action.SUCCESS;

	}

	@Override
	public String logout(Object operator) {
		if (null != operator) {
			// Struts2Utils.getSession().removeAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
			Struts2Utils.removeSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);

			Cookie cookie = new Cookie(COOKIE_NAME, null);
			cookie.setMaxAge(0);
			Struts2Utils.getResponse().addCookie(cookie);

		}
		return Action.SUCCESS;

	}

	/**
	 * 创建登录日志，采用异步的方式插入到数据
	 * 
	 * @param userid
	 *            工号
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-9-12 下午02:58:02
	 * @version V1.0
	 */
	public void createLoginLog(String userid) {
		LoginLogVO loginlogVO = new LoginLogVO();
		loginlogVO.setSysloginid(Sequence.getSequence());
		loginlogVO.setOpercode(userid);
		loginlogVO.setLoginTime(new Date());
		String ip = IPUtil.getClientIP(Struts2Utils.getRequest());
		loginlogVO.setLoginIp(ip);

		try {
			AsynchronousTaskFactory.getFactory().createVO(loginlogVO);
		} catch (TaskException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 用户三级菜单查询
	 */
	@Override
	public List<MenuVO> queryThirdChildMenu(UserVO userVO, String menuId, List groupids, String type, String from) {

		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		List<MenuVO> menuList = null;
		List<MenuVO> menuReturnList = new ArrayList<MenuVO>();
		String likeMenuId = menuId + "%";// 用like进行查询
		if (Integer.valueOf(from) == 0 && userVO.getIsManager()) {
			sb.append(" SELECT menu FROM ");
			sb.append(MenuVO.class.getName()).append(" as menu ");
			sb.append(" WHERE ");
			sb.append(" menu.status = ? ");
			// sb.append(" AND menu.controlid like ? ");
			sb.append(" and menu.menutype = '3' ");
			sb.append(" and menu.type = ? ");
			sb.append(" AND menu.pcontrolid like ? ");
			menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(),
			// new Object[] {
			// WebConstants.STATUS_VALID,likeMenuId,WebConstants.MENUTYPE_MENU,likeMenuId});
					new Object[] { WebConstants.STATUS_VALID, WebConstants.MENUTYPE_MENU, likeMenuId });
		} else {

			// 用户组id关联菜单控制点
			List groups = null;
			if (Integer.valueOf(type) == 1) {
				groups = userVO.getGourpIdList();
			} else {
				groups = groupids;
			}

			sb.append(" select menu.* from  sys_control menu,  sys_usergroup_control g where ");
			sb.append(" menu.controlid = g.controlid ");
			sb.append(" and menu.pcontrolid = ? ");
			sb.append(" and menu.menutype = '3' ");
			sb.append(" and menu.type = ? ");
			sb.append(" and menu.status = ? ");
			sb.append(" and g.groupid in ('");
			if (!CollectionUtils.isEmpty(groups)) {
				List tempList = new ArrayList(groups);
				sb.append(StringUtils.join(tempList, "','"));
				tempList.clear();
			} else {
				sb.append("-1");
			}
			sb.append("') ");
			sb.append(" order by orderby asc ");
			Session session = queryDao.getSession();
			SQLQuery query = session.createSQLQuery(sb.toString());
			query.addEntity("menu", MenuVO.class);
			query.setString(0, menuId).setString(1, WebConstants.MENUTYPE_MENU).setString(2, WebConstants.STATUS_VALID);
			menuList = query.list();
		}

		// Map<String, MenuVO> menuMap = new TreeMap<String, MenuVO>();
		menuReturnList.clear();
		for (MenuVO menuVO : menuList) {
			// menuMap.put(menuVO.getControlid(), menuVO);
			// System.out.println(menuVO.getLname());
			menuReturnList.add(menuVO);
		}
		return menuReturnList;
	}

	/**
	 * 用户二级菜单查询
	 */
	@Override
	public List<MenuVO> querySecondChildMenu(UserVO userVO, String menuId, List groupids, String type, String from) {

		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		List<MenuVO> menuList = null;
		List<MenuVO> menuReturnList = new ArrayList<MenuVO>();
		// List<MenuVO> menuChildList = new ArrayList<MenuVO>();
		// List<MenuVO> menuChildListAll = new ArrayList<MenuVO>();
		String likeMenuId = menuId + "%";// 用like进行查询
		if (Integer.valueOf(from) == 0 && userVO.getIsManager()) {
			sb.append(" SELECT menu FROM ");
			sb.append(MenuVO.class.getName()).append(" as menu ");
			sb.append(" WHERE ");
			sb.append(" menu.status = ? ");
			// sb.append(" AND menu.controlid like ? "); // 菜单状态有效
			sb.append(" and menu.menutype = '2' ");
			sb.append(" and menu.type = ? ");
			sb.append(" AND menu.pcontrolid like ? ");
			menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(),
			// new Object[] {
			// WebConstants.STATUS_VALID,likeMenuId,WebConstants.MENUTYPE_MENU,likeMenuId});
					new Object[] { WebConstants.STATUS_VALID, WebConstants.MENUTYPE_MENU, likeMenuId });
		} else {

			// 用户组id关联菜单控制点
			List groups = null;
			if (Integer.valueOf(type) == 1) {
				groups = userVO.getGourpIdList();
			} else {
				groups = groupids;
			}
			sb.append(" select menu.* from  sys_control menu, sys_usergroup_control g where ");
			sb.append(" menu.controlid = g.controlid ");
			sb.append(" and menu.pcontrolid = ? ");
			sb.append(" and menu.menutype = '2' ");
			sb.append(" and menu.type = ? ");
			sb.append(" and menu.status = ? ");
			sb.append(" and g.groupid in ('");
			if (!CollectionUtils.isEmpty(groups)) {
				List tempList = new ArrayList(groups);
				sb.append(StringUtils.join(tempList, "','"));
				tempList.clear();
			} else {
				sb.append("-1");
			}
			sb.append("') ");
			sb.append(" order by orderby asc ");
			Session session = queryDao.getSession();
			SQLQuery query = session.createSQLQuery(sb.toString());
			query.addEntity("menu", MenuVO.class);
			query.setString(0, menuId).setString(1, WebConstants.MENUTYPE_MENU).setString(2, WebConstants.STATUS_VALID);
			menuList = query.list();
		}

		menuReturnList.clear();
		for (MenuVO menuVO : menuList) {
			menuReturnList.add(menuVO);
		}
		return menuReturnList;
	}

	/*
	 * 用户一级菜单查询 (non-Javadoc)
	 */
	@Override
	public List<MenuVO> queryTopMenu(UserVO userVO, List groupids, String type, String from) {
		List<MenuVO> menuList = null;
		/**
		 * 用户一级菜单查询
		 */
		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(UserVO.class);
		if (Integer.valueOf(from) == 0 && userVO.getIsManager()) { // 超级用户
			sb.append(" SELECT menu FROM ");
			sb.append(MenuVO.class.getName()).append(" as menu ");
			sb.append(" WHERE ");
			sb.append(" menu.status = ? ");
			sb.append(" AND menu.pcontrolid = ? "); // 菜单状态有效
			sb.append(" and menu.type = ? ");
			sb.append(" order by menu.orderby asc");

			menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(), new Object[] { WebConstants.STATUS_VALID,
					Constants.ROOT_MENU_ID, WebConstants.MENUTYPE_MENU });

		} else {
			// 用户组id关联菜单控制点
			List groups = null;
			if (Integer.valueOf(type) == 1) {
				groups = userVO.getGourpIdList();
			} else {
				groups = groupids;
			}

			sb.append(" select menu.* from  sys_control menu, sys_usergroup_control g where ");
			sb.append("  menu.controlid = g.controlid ");
			sb.append(" and menu.pcontrolid = ? ");
			sb.append(" and menu.type = ? ");
			sb.append(" and menu.status = ? ");
			sb.append(" and g.groupid in ('");
			if (!CollectionUtils.isEmpty(groups)) {
				List tempList = new ArrayList(groups);
				sb.append(StringUtils.join(tempList, "','"));
				tempList.clear();
			} else {
				sb.append("-1");
			}
			sb.append("') ");
			sb.append(" order by orderby asc ");
			Session session = queryDao.getSession();
			SQLQuery query = session.createSQLQuery(sb.toString());
			query.addEntity("menu", MenuVO.class);
			query.setString(0, Constants.ROOT_MENU_ID).setString(1, WebConstants.MENUTYPE_MENU)
					.setString(2, WebConstants.STATUS_VALID);
			menuList = query.list();
		}

		HibernateDAO queryDao1 = DAOFactory.getInstance().createHibernateDAO(AttachVO.class);
		for (MenuVO menuVO : menuList) {// 主要是获取图片的路径地址
			StringBuffer sp = new StringBuffer();
			Long icon = menuVO.getIcon();
			if (icon != null) {
				sp.append(" FROM AttachVO as attach ");
				sp.append(" WHERE ");
				sp.append(" attach.attId = ? ");
				List<AttachVO> attachList = (List<AttachVO>) queryDao1.findByHQL(sp.toString(), new Object[] { icon });
				AttachVO attachVO = null;
				if (attachList != null && attachList.size() > 0) {
					attachVO = attachList.get(0);
					String iconPath = attachVO.getSavepath();
					menuVO.setIconPath(iconPath);
				}
			}
		}
		return menuList;

	}

	public List<MenuVO> queryChildMenu(UserVO userVO, String menuId) {

		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		List<MenuVO> menuList = null;
		String likeMenuId = menuId + "%";// 用like进行查询
		if (userVO.getIsManager()) {
			sb.append(" SELECT menu FROM ");
			sb.append(MenuVO.class.getName()).append(" as menu ");
			sb.append(" WHERE ");
			sb.append(" menu.status = ? "); // 菜单状态有效
			sb.append(" AND menu.controlid like ? ");
			sb.append(" and menu.type = ? ");
			sb.append(" AND menu.pcontrolid like ? ");
			menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(), new Object[] { WebConstants.STATUS_VALID,
					likeMenuId, WebConstants.MENUTYPE_MENU, likeMenuId });
		} else {

			// 用户组id关联菜单控制点
			List groups = userVO.getGourpIdList();
			sb.append(" select menu.* from  sys_control menu,  sys_usergroup_control g where ");
			sb.append("  menu.controlid = g.controlid ");
			sb.append(" and menu.pcontrolid = ? ");
			sb.append(" and menu.type = ? ");
			sb.append(" and menu.status = ? ");
			sb.append(" and g.groupid in ('");
			if (!CollectionUtils.isEmpty(groups)) {
				List tempList = new ArrayList(groups);
				sb.append(StringUtils.join(tempList, "','"));
				tempList.clear();
			} else {
				sb.append("-1");
			}
			sb.append("') ");
			sb.append(" order by orderby asc ");
			Session session = queryDao.getSession();
			SQLQuery query = session.createSQLQuery(sb.toString());
			query.addEntity("menu", MenuVO.class);
			query.setString(0, menuId).setString(1, WebConstants.MENUTYPE_MENU).setString(2, WebConstants.STATUS_VALID);
			menuList = query.list();
		}

		Map<String, MenuVO> menuMap = new TreeMap<String, MenuVO>();
		for (MenuVO menuVO : menuList) {
			menuMap.put(menuVO.getControlid(), menuVO);
		}
		menuList.clear();
		menuList.addAll(menuMap.values());
		return menuList;
	}

	/**
	 * 所有三级菜单查询
	 */
	@Override
	public List<MenuVO> queryThirdChildMenuAll(UserVO userVO, String menuId) {

		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		List<MenuVO> menuList = null;
		List<MenuVO> menuReturnList = new ArrayList<MenuVO>();
		String likeMenuId = menuId + "%";// 用like进行查询
		// 角色id关联控制点
		sb.append(" SELECT menu FROM ");
		sb.append(MenuVO.class.getName()).append(" as menu ");
		sb.append(" WHERE ");
		sb.append(" menu.status = ? "); // 菜单状态有效
		sb.append(" AND menu.controlid like ? ");
		sb.append(" and menu.type = ? ");
		sb.append(" AND menu.pcontrolid like ? ");
		menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(), new Object[] { WebConstants.STATUS_VALID,
				likeMenuId, WebConstants.MENUTYPE_MENU, likeMenuId });

		menuReturnList.clear();
		for (MenuVO menuVO : menuList) {
			menuReturnList.add(menuVO);
		}
		return menuReturnList;
	}

	/**
	 * 所有二级菜单查询
	 */
	@Override
	public List<MenuVO> querySecondChildMenuAll(UserVO userVO, String menuId) {

		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		List<MenuVO> menuList = null;
		List<MenuVO> menuReturnList = new ArrayList<MenuVO>();

		String likeMenuId = menuId + "%";// 用like进行查询
		// 角色id关联控制点
		sb.append(" SELECT menu FROM ");
		sb.append(MenuVO.class.getName()).append(" as menu ");
		sb.append(" WHERE ");
		sb.append(" menu.status = ? "); // 菜单状态有效
		sb.append(" AND menu.controlid like ? ");
		sb.append(" and menu.type = ? ");
		sb.append(" AND menu.pcontrolid like ? ");
		menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(), new Object[] { WebConstants.STATUS_VALID,
				likeMenuId, WebConstants.MENUTYPE_MENU, likeMenuId });

		menuReturnList.clear();
		for (MenuVO menuVO : menuList) {
			menuReturnList.add(menuVO);
		}
		return menuReturnList;
	}

	/*
	 * 所有一级菜单查询 (non-Javadoc)
	 */
	@Override
	public List<MenuVO> queryTopMenuAll(UserVO userVO) {
		List<MenuVO> menuList = null;
		/**
		 * 所有一级菜单查询
		 */
		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(UserVO.class);

		sb.append(" SELECT menu FROM ");
		sb.append(MenuVO.class.getName()).append(" as menu ");
		sb.append(" WHERE ");
		sb.append(" menu.status = ? ");
		sb.append(" AND menu.pcontrolid = ? "); // 菜单状态有效
		sb.append(" and menu.type = ? ");
		sb.append(" order by menu.orderby asc");

		menuList = (List<MenuVO>) queryDao.findByHQL(sb.toString(), new Object[] { WebConstants.STATUS_VALID,
				Constants.ROOT_MENU_ID, WebConstants.MENUTYPE_MENU });

		HibernateDAO queryDao1 = DAOFactory.getInstance().createHibernateDAO(AttachVO.class);
		for (MenuVO menuVO : menuList) {// 主要是获取图片的路径地址
			StringBuffer sp = new StringBuffer();
			Long icon = menuVO.getIcon();
			if (icon != null) {
				sp.append(" FROM AttachVO as attach ");
				sp.append(" WHERE ");
				sp.append(" attach.attId = ? ");
				List<AttachVO> attachList = (List<AttachVO>) queryDao1.findByHQL(sp.toString(), new Object[] { icon });
				AttachVO attachVO = null;
				if (attachList != null && attachList.size() > 0) {
					attachVO = attachList.get(0);
					String iconPath = attachVO.getSavepath();
					menuVO.setIconPath(iconPath);
				}
			}
		}
		return menuList;

	}

	/*
	 * 新增用户权限菜单 (non-Javadoc)
	 */
	@Override
	public void addUserMenuList(List addUserMenuList, String groupid, String creator) {
		if (addUserMenuList == null || groupid == null) {
			return;
		}
		try {
			Date currentTime = new Date();
			for (int i = 0; i < addUserMenuList.size(); i++) {
				UsergroupControlVO entity = new UsergroupControlVO();
				entity.setGroupid(Long.valueOf(groupid));
				entity.setControlid(String.valueOf(addUserMenuList.get(i)));
				entity.setCreator(creator);
				entity.setCreatetime(currentTime);
				this.getService().doCreate(UsergroupControlVO.class, entity);
			}

		} catch (Exception e) {
			// 控制台输出错误信息
			System.out.println("添加时发生错误:" + e);

		}

	}

	/*
	 * 删除用户权限菜单 (non-Javadoc)
	 */
	@Override
	public void delUserMenuList(List addUserMenuList, String groupid) {
		if (addUserMenuList == null || groupid == null) {
			return;
		}
		try {
			for (int i = 0; i < addUserMenuList.size(); i++) {
				// this.getService().doRemoveByVO(UsergroupControlVO.class,
				// entity);
				getService().executeHQLUpdate("delete UsergroupControlVO vo where vo.controlid = ? and vo.groupid = ?",
						new Object[] { String.valueOf(addUserMenuList.get(i)), Long.valueOf(groupid) });
			}

		} catch (Exception e) {
			// 控制台输出错误信息
			System.out.println("删除时发生错误:" + e);

		}

	}

	/**
	 * Action 错误信息
	 * 
	 * @param @param errorMessage
	 * @return void
	 * @throws
	 */
	protected void addErrorMessage(String errorMessage) {
		if (StringUtils.isNotBlank(errorMessage)) {
			List<String> msgList = (List<String>) Struts2Utils.getRequest().getAttribute(WebConstants.ERROR_MESSAGE);
			if (null != msgList && msgList.size() > 0) {
				msgList.add(errorMessage);
			} else {
				msgList = new ArrayList<String>();
				msgList.add(errorMessage);
				Struts2Utils.getRequest().setAttribute(WebConstants.ERROR_MESSAGE, msgList);
			}
		}
	}

	/**
	 * Action 操作信息
	 * 
	 * @param @param successMessage
	 * @return void
	 * @throws
	 */
	protected void addMessage(String successMessage) {
		if (StringUtils.isNotBlank(successMessage)) {
			List<String> msgList = (List<String>) Struts2Utils.getRequest().getAttribute(WebConstants.DEFAULT_MESSAGE);
			if (null != msgList && msgList.size() > 0) {
				msgList.add(successMessage);
			} else {
				msgList = new ArrayList<String>();
				msgList.add(successMessage);
				Struts2Utils.getRequest().setAttribute(WebConstants.DEFAULT_MESSAGE, msgList);
			}
		}
	}

	protected CommonService getService() {
		return service;
	}

	@Autowired
	@Qualifier("commonServiceImpl")
	protected void setService(CommonService service) {
		this.service = service;
	}

	/**
	 * 获取所有适合的菜单项
	 */
	@Override
	public List<MenuVO> queryMenuAll() {
		List<MenuVO> menuList = null;
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		menuList = (List<MenuVO>) queryDao.findByHQL("SELECT menu FROM " + MenuVO.class.getName()
				+ " AS menu WHERE  menu.status ='" + WebConstants.STATUS_VALID + "' AND menu.type = '"
				+ WebConstants.MENUTYPE_MENU + "' order by menu.orderby asc");
		return menuList;

	}

	/**
	 * 菜单项中menutype的最大值
	 * 
	 */
	@Override
	public int MaxMenuType(List<MenuVO> list) {
		Session session = DAOFactory.getInstance().createHibernateDAO(MenuVO.class).getSession();
		String l = (String) session.createQuery("select max(a.menutype) from MenuVO a ").uniqueResult();
		int max = Integer.parseInt(l);
		return max;
	}

	// 非管理员 过滤查询菜单
	@Override
	public List<MenuVO> queryMenuByGroupids(List<Long> gourpIdList) {
		List<MenuVO> menuList = null;
		StringBuffer sb = new StringBuffer();
		HibernateDAO queryDao = DAOFactory.getInstance().createHibernateDAO(MenuVO.class);
		sb.append(" select menu.* from  sys_control menu, sys_usergroup_control g where ");
		sb.append(" menu.controlid = g.controlid ");
		sb.append(" and menu.type = '" + WebConstants.MENUTYPE_MENU + "' ");
		sb.append(" and menu.status = '" + WebConstants.STATUS_VALID + "' ");
		sb.append(" and g.groupid in ('");
		if (!CollectionUtils.isEmpty(gourpIdList)) {
			List tempList = new ArrayList(gourpIdList);
			sb.append(StringUtils.join(tempList, "','"));
			tempList.clear();
		} else {
			sb.append("-1");
		}
		sb.append(" ')  order by orderby asc ");
		SQLQuery query = queryDao.getSession().createSQLQuery(sb.toString());
		query.addEntity("menu", MenuVO.class);
		menuList = query.list();
		return menuList;

	}

}
